# 等腰三角形(不懂)
# 2025/3/26
import bisect

def min_operations(a):
    a.sort()
    n = len(a)
    a = [0] + a
    sum_a = [0] * (n + 1)  # 前缀和数组

    for i in range(1, n + 1):
        sum_a[i] = sum_a[i - 1] + a[i]

    ans = float('inf')

    # 小的数只有一个
    mid = (2 + n) // 2
    ans = min(ans, (sum_a[n] - sum_a[mid]) - (n - mid) * a[mid] + (mid - 2) * a[mid] - (sum_a[mid - 1] - sum_a[1]))

    # 未卡到边界
    def cal(l, r):
        mid = (l + r) // 2
        res = (sum_a[r] - sum_a[mid] - (r - mid) * a[mid] + (mid - (l - 1)) * a[mid] - (sum_a[mid] - sum_a[l - 1]))
        return res

    def get_mid(l, r):
        mid = (l + r) // 2
        if (l + r) % 2 == 1:
            return a[mid], a[mid + 1]
        else:
            return a[mid], a[mid]

    ans = min(ans, cal(1, n))

    for i in range(1, n):
        l1, r1 = get_mid(1, i)
        l2, r2 = get_mid(i + 1, n)

        if 2 * r1 > l2:
            ans = min(ans, cal(1, i) + cal(i + 1, n))

    # 枚举左右端点
    def S(l, r):
        if l > r:
            return 0, 0
        pr = bisect.bisect_right(a, r, lo=1) - 1
        pl = bisect.bisect_left(a, l, lo=1) - 1
        return sum_a[pr] - sum_a[pl], pr - pl

    def calculate(x, y):
        if 2 * x <= y:
            return
        mid = (x + y) // 2
        res = 0
        s1, num1 = S(0, x - 1)
        res += x * num1 - s1
        s2, num2 = S(x, mid)
        res += s2 - x * num2
        s3, num3 = S(mid + 1, y)
        res += y * num3 - s3
        s4, num4 = S(y + 1, 2e9)
        res += s4 - y * num4
        nonlocal ans
        ans = min(ans, res)

    # 枚举左端点
    for i in range(1, n + 1):
        calculate(a[i], 2 * a[i] - 1)

    # 枚举右端点
    for i in range(1, n + 1):
        calculate((a[i] + 1) // 2 + 1, a[i] + 1)
        calculate(a[i] // 2 + 1, a[i])
        calculate(a[i] // 2, a[i] - 1)
        calculate(a[i] // 2, a[i] - 2)

    return ans

if __name__ == '__main__':
    print(min_operations([3, 3, 5, 7, 7]))
